;(function (window) {
	'use strict'

	// Your starting point. Enjoy the ride!
	//TODO: Selectors
	var todoInput = document.querySelector('.new-todo')
	var todoList = document.querySelector('.todo-list')
	var clear_completed = document.querySelector('.clear-completed')
	//NOTE: 下面这个可以记下笔记
	// var toggle_all = document.querySelector('label[for="toggle-all"]')
	var toggle_all = document.querySelector('.toggle-all')
	var footer = document.querySelector('footer')

	//TODO: Event Listener
	todoInput.addEventListener('keydown', addTodo)
	document.addEventListener('DOMContentLoaded', checkClearCompleted)
	document.addEventListener('DOMContentLoaded', getTodos)
	document.addEventListener('DOMContentLoaded', countTodo)
	window.addEventListener('DOMContentLoaded', checkFooterDisplay)
	todoList.addEventListener('change', checkClearCompleted)
	todoList.addEventListener('click', actionCheck)
	todoList.addEventListener('dblclick', editTodo)
	todoList.addEventListener('keyup', editTodo)
	//IMPORTANT: 这个focusout事件是关键
	todoList.addEventListener('focusout', onEditFocusout)
	clear_completed.addEventListener('click', clearCompleted)
	toggle_all.addEventListener('click', toggleAll)
	toggle_all.addEventListener('click', countTodo)
	toggle_all.addEventListener('click', checkClearCompleted)
	//hash路由
	window.addEventListener('hashchange', showRouter)
	//TODO: Functions
	function addTodo(event) {
		var li = document.createElement('li')

		var div = document.createElement('div')
		div.classList.add('view')
		li.appendChild(div)

		var input = document.createElement('input')
		input.classList.add('toggle')
		input.type = 'checkbox'
		div.appendChild(input)

		var label = document.createElement('label')
		label.innerText = todoInput.value
		div.appendChild(label)

		var button = document.createElement('button')
		button.classList.add('destroy')
		div.appendChild(button)

		if (event.keyCode === 13 && todoInput.value !== '') {
			todoList.appendChild(li)
			saveLocalTodos(todoInput.value)
			todoInput.value = ''
			countTodo()
			checkFooterDisplay()
		}
	}

	function actionCheck(event) {
		var li = event.target.parentElement.parentElement
		switch (event.target.classList[0]) {
			case 'toggle':
				var label_content = event.target.nextSibling.innerText
				updateLocalTodos(event.target.checked, label_content)
				li.classList.toggle('completed')
				break
			case 'destroy':
				var label_content = event.target.previousSibling.innerText
				deleteLocalTodos(label_content)
				li.remove()
		}
		countTodo()
		checkFooterDisplay()
	}

	function clearCompleted() {
		var todos = Array.prototype.slice.call(todoList.children)
		todos.forEach(function (todo) {
			if (todo.classList[0] === 'completed') {
				deleteLocalTodos(todo.querySelector('label').innerText)
				todo.remove()
			}
		})
		countTodo()
		checkFooterDisplay()
	}

	function toggleAll() {
		var todos = [].slice.call(todoList.children)

		//NOTE: 这叫Element.querySelector()
		var completed = todoList.querySelectorAll('.completed').length

		var total = todos.length
		if (completed < total) {
			todos.forEach(function (todo) {
				if (!todo.classList.contains('completed')) {
					todo.classList.add('completed')
					todo.querySelector('.toggle').checked = true
					updateLocalTodos(
						todo.querySelector('.toggle').checked,
						todo.querySelector('label').innerText
					)
				}
			})
		} else {
			todos.forEach(function (todo) {
				todo.classList.remove('completed')
				todo.querySelector('.toggle').checked = false
				updateLocalTodos(
					todo.querySelector('.toggle').checked,
					todo.querySelector('label').innerText
				)
			})
		}
	}

	function editTodo(event) {
		var listItem = event.target.parentElement.parentElement
		switch (event.target.tagName) {
			case 'LABEL':
				listItem.classList.add('editing')
				var input = document.createElement('input')
				//NOTE: className和classList的区别？
				input.className = 'edit'
				//IMPORTANT: innerText和textContent的不同?
				input.value = event.target.innerText
				listItem.appendChild(input)
				input.focus()
				break
		}
		if (event.keyCode === 13) {
			listItem.querySelector('.edit').blur()
		}
	}

	function onEditFocusout() {
		var editInput = document.querySelector('.edit')
		//NOTE: 这里的event.target永远是<input class="edit">
		if (editInput && editInput.value) {
			updateLocalTodos(
				editInput.parentElement.querySelector('.toggle').checked,
				editInput.parentElement.querySelector('label').innerText,
				editInput.value
			)
			editInput.parentElement.classList.remove('editing')
			editInput.parentElement.querySelector('label').innerText =
				editInput.value
			editInput.blur()
			editInput.remove()
		}
	}

	function checkClearCompleted() {
		var todos = todoList.childNodes
		//NOTE:forEach循环没有返回值；forEach会一直循环完所有元素，没有跳出条件，即没有break和continue
		for (var i = 0; i < todos.length; i++) {
			if (
				todos[i].classList &&
				todos[i].classList.contains('completed')
			) {
				clear_completed.style.display = 'block'
				break
			} else {
				clear_completed.style.display = 'none'
			}
		}
	}

	function countTodo() {
		var todo_count = document.querySelector('.todo-count strong')
		var todos = todoList.childNodes
		var count = 0
		todos.forEach(function (todo) {
			if (todo.classList && !todo.classList.contains('completed')) {
				count++
			}
		})
		todo_count.innerText = count
	}

	function saveLocalTodos(todo) {
		var todos
		if (localStorage.getItem('todos') === null) {
			todos = []
		} else {
			todos = JSON.parse(localStorage.getItem('todos'))
		}
		todos.push({ title: todo, done: false })
		localStorage.setItem('todos', JSON.stringify(todos))
	}

	function getTodos() {
		var todos
		if (localStorage.getItem('todos') === null) {
			todos = []
		} else {
			todos = JSON.parse(localStorage.getItem('todos'))
		}
		todos.forEach(function (todo) {
			var li = document.createElement('li')
			if (todo.done) {
				li.classList.add('completed')
			} else {
				li.classList.remove('completed')
			}

			var div = document.createElement('div')
			div.classList.add('view')
			li.appendChild(div)

			var input = document.createElement('input')
			input.classList.add('toggle')
			input.type = 'checkbox'
			input.checked = todo.done
			div.appendChild(input)

			var label = document.createElement('label')
			label.innerText = todo.title
			div.appendChild(label)

			var button = document.createElement('button')
			button.classList.add('destroy')
			div.appendChild(button)

			todoList.appendChild(li)
		})
	}

	function deleteLocalTodos(todo) {
		var todos
		todos = JSON.parse(localStorage.getItem('todos'))
		todos = todos.filter(function (item) {
			return item.title !== todo
		})
		localStorage.setItem('todos', JSON.stringify(todos))
	}

	function updateLocalTodos(status, oldValue, newValue) {
		var todos
		todos = JSON.parse(localStorage.getItem('todos'))
		todos.forEach(function (item) {
			if (item.title === oldValue) {
				item.title = newValue || oldValue
				item.done = status
			}
		})
		localStorage.setItem('todos', JSON.stringify(todos))
	}

	function checkFooterDisplay() {
		var todo_count = document.querySelector('.todo-list').childElementCount
		console.log('todo_count: ', todo_count);
		if (todo_count > 0) {
			footer.style.display = 'block'
		} else {
			footer.style.display = 'none'
		}
	}

	function showRouter() {
		var hash = window.location.hash
		console.log('hash: ', hash)
		var hashValue = hash.replace('#/', '')
		console.log('hashValue: ', hashValue)
	}
})(window)
